package com.stg.service.impl;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.stg.bean.User;
import com.stg.service.RegiserValidateService;
import com.stg.service.UserService;
import com.stg.util.SendEmail;

@Service("regiserValidateService")
public class RegiserValidateServiceImpl implements RegiserValidateService{
	 
	    @Resource
	    private UserService userService;
	    @Resource
	    private SendEmail sendEmail;
	 
	    /**
	     * 处理注册
	    */
	    public void processregister(User user){
	        
	        //加密激活码
	        user.setValidateCode(Encrypt(user.getUsername(),"SHA-384"));
	        user.setValidateStatus(0);
	        System.out.println("采用SHA-384加密之后的串为："+user.getValidateCode());
	 
	        userService.createUser(user);//保存注册信息
	 
	        //邮件的内容
	        StringBuffer sb=new StringBuffer("<h1 align=\"center\">社团管理系统</h1><br><p>尊敬的");
			sb.append(user.getUsername());
			sb.append("您已经注册成功请点击下面链接激活账号，48小时生效，否则重新注册账号，链接只能使用一次，请尽快激活！</br>");
	        sb.append("<a href=\"http://localhost:8080/pms/user/registerValidate?email=");
	        sb.append(user.getUsername());
	        sb.append("&validateCode=");
	        sb.append(user.getValidateCode());
	        sb.append("\">http://localhost:8080/pms/user/registerValidate?email=");
	        sb.append(user.getUsername());
	        sb.append("&validateCode=");
	        sb.append(user.getValidateCode());
	        sb.append("</a></p>");
	 
	        //发送邮件
	        sendEmail.send(user.getUsername(), sb.toString());
	        System.out.println("发送邮件");
	 
	    }
	 
	    /**
	     * 处理激活
	     * @throws ParseException
	     */
	      ///传递激活码和email过来
	    public String processActivate(String username , String validateCode){ 
	         //数据访问层，通过email获取用户信息
	    	String meg = "你已成功激活账户，现在可以登录了！";
	        User user=userService.findByUsername(username);
	        System.out.println(user);
	        System.out.println(validateCode);
	        //验证用户是否存在
	        if(user!=null) {
	            //验证用户激活状态 
	            if(user.getValidateStatus()==0) {
	                //没激活
	            	
	                //验证链接是否过期
	                /*if(new Date().before(user.getCreateTime())) {*/
	                    //验证激活码是否正确 
	                    if(validateCode.equals(user.getValidateCode())) {
	                        //激活成功， //并更新用户的激活状态，为已激活
	                        System.out.println("==sq==="+user.getStatus());
	                        user.setStatus(1);//把状态改为激活
	                        System.out.println("==sh==="+user.getStatus());
	                        userService.updateValidateStatus(user);
	                    } else {
	                    	System.out.println("激活码不正确");
	                    	meg = "激活码不正确";
	                    } 
	                /*} else { System.out.println("激活码已过期");
	                			meg = "激活码已过期";
	                } */
	            } else {
	               System.out.println("邮箱已激活，请登录！");
	               meg = "邮箱已激活，请登录！";
	            } 
	        } else {
	        		System.out.println("该邮箱未注册（邮箱地址不存在）！");
	        		meg = "该邮箱未注册（邮箱地址不存在）！";
	        } 
	 
	        return meg;
	    }
	    
	    //数字签名     
        public String Encrypt(String strSrc, String encName) {
            MessageDigest md = null;
            String strDes = null;
            byte[] bt = strSrc.getBytes();
            try {
                md = MessageDigest.getInstance(encName);
                md.update(bt);
                strDes = bytes2Hex(md.digest()); // to HexString
            } catch (NoSuchAlgorithmException e) {
                System.out.println("签名失败！");
                return null;
            }
            return strDes;
        }
        
        public String bytes2Hex(byte[] bts) {
            String des = "";
            String tmp = null;
            for (int i = 0; i < bts.length; i++) {
                tmp = (Integer.toHexString(bts[i] & 0xFF));
                if (tmp.length() == 1) {
                    des += "0";
                }
                des += tmp;
            }
            return des;
        }
}
